import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/login/index.vue'
import Register from '@/views/register/index.vue'
import Category from '@/views/category'
import ArticleList from '@/views/articleList'
import PublishArticle from '@/views/publishArticle'
import User from '@/views/user'
import Avatar from '@/views/avatar'
import ResetPwd from '@/views/resetPwd'
import store from '@/store'

Vue.use(VueRouter)

const routes = [
  { path: '/login', component: Login },
  { path: '/register', component: Register },
  {
    path: '/',
    component: () => import('@/views/layout'),
    redirect: '/home', // 默认显示首页的二级路由
    children: [
      {
        path: 'home',
        component: () => import('@/views/home')
      },
      { path: '/art-cate', component: Category },
      {
        path: '/art-list',
        component: ArticleList,
        children: [
          { path: '/publish', component: PublishArticle }
        ]
      },
      { path: '/user-info', component: User },
      { path: '/user-avatar', component: Avatar },
      { path: '/user-pwd', component: ResetPwd }
    ]
  }
]

const router = new VueRouter({
  routes
})
const whileList = ['/login', '/register']

// 路由导航守卫
router.beforeEach((to, from, next) => {
  // console.log(to.path)
  const token = store.state.user.token
  if (token) {
    return next()
  }

  if (whileList.includes(to.path)) {
    // location.reload()
    next()
    return
  }

  next('/login')
})
export default router
